package com.johndriver.selenium.wait;

import com.google.common.base.Function;
import com.johndriver.selenium.driver.DriverDemo;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.context.annotation.Bean;

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.regex.Pattern;

/**
 * 等待案例
 * 日期 2021/5/22 19:03
 * 创建者：john driver
 */
public class WaitDemo {
    public static void main(String[] args) {
        final WebDriver driver = DriverDemo.driver();
        driver.get("https://google.com/ncr");
        driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);
        //10s内，等待By.xpath("//a/h3")这个元素可以点击的条件发生。
        WebElement firstResult = new WebDriverWait(driver, 10)
                .until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")));
        System.out.println(firstResult.getText());
        final WebElement element = driver.findElement(By.id("element"));
        //元素可点击
        ExpectedConditions.elementToBeClickable(By.id("element"));
        ExpectedConditions.elementToBeClickable(element);
        //元素存在
        ExpectedConditions.presenceOfElementLocated(By.id("element"));
        //元素中存在文字
        ExpectedConditions.textToBePresentInElement(element,"元素中的文字");
        //元素可不可见
        ExpectedConditions.visibilityOfElementLocated(By.id("element"));
        ExpectedConditions.invisibilityOfElementLocated(By.id("element"));
        ExpectedConditions.visibilityOf(element);
        ExpectedConditions.visibilityOfNestedElementsLocatedBy(By.id("parent"),By.id("child"));
        //元素的某个属性是不是这个值
        ExpectedConditions.attributeToBe(element,"href","www.baidu.com");
        //元素中是否有值为"www.baidu.com"的href属性
        ExpectedConditions.attributeContains(element,"href","www.baidu.com");
        //frame是否可用并转入
        ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("frame"));
        //标题条件
        ExpectedConditions.titleIs("标题");

        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(Duration.ofSeconds(30))//等待30s
                .pollingEvery(Duration.ofSeconds(5))//5秒尝试访问一次
                .ignoring(NoSuchElementException.class);//忽略访问时找不到元素异常

        WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.id("foo"));
            }
        });
        final Rectangle rect = element.getRect();
        rect.getX();
        rect.getY();
        rect.getWidth();
        rect.getHeight();
    }
}

